import csv
import time
import os
import logging
from datetime import datetime
from typing import Dict, Any, Optional, List


class DataLogger:
    def __init__(self):
        self.log_file = None
        self.csv_writer = None
        self.is_logging = False
        self.filename = None
        self.fieldnames = None

        # 设置日志
        self.logger = logging.getLogger('LiquidCooler.DataLogger')

    def start_logging(self, filename: str, fieldnames: Optional[List[str]] = None) -> bool:
        """开始记录数据"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(filename) if os.path.dirname(filename) else '.', exist_ok=True)

            # 设置日志文件大小限制
            max_file_size = 10 * 1024 * 1024  # 10MB
            if os.path.exists(filename) and os.path.getsize(filename) > max_file_size:
                self.logger.warning(f"日志文件大小超过限制，将清空文件: {filename}")
                open(filename, 'w').close()

            self.log_file = open(filename, 'w', newline='', encoding='utf-8')
            self.fieldnames = ['Timestamp', 'DateTime'] + (fieldnames if fieldnames else [
                'Temperature', 'Pressure', 'Flow', 'Setpoint', 'Power', 'Status'
            ])

            self.csv_writer = csv.DictWriter(self.log_file, fieldnames=self.fieldnames)
            self.csv_writer.writeheader()
            self.filename = filename
            self.is_logging = True

            self.logger.info(f"数据记录已启动: {filename}")
            return True

        except Exception as e:
            self.logger.error(f"启动数据记录失败: {str(e)}")
            self._cleanup()
            return False

    def stop_logging(self) -> bool:
        """停止记录数据"""
        try:
            if self.log_file:
                self.log_file.close()
                self.logger.info(f"数据记录已停止: {self.filename}")

            self._cleanup()
            return True

        except Exception as e:
            self.logger.error(f"停止数据记录失败: {str(e)}")
            return False

    def log_data(self, data: Dict[str, Any]) -> bool:
        """记录数据"""
        if not self.is_logging or not self.csv_writer:
            self.logger.warning("数据记录器未启动，无法记录数据")
            return False

        try:
            timestamp = time.time()
            dt = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

            row_data = {'Timestamp': timestamp, 'DateTime': dt}

            # 添加数据字段
            for field in self.fieldnames[2:]:
                row_data[field] = data.get(field, '')

            self.csv_writer.writerow(row_data)
            self.log_file.flush()

            return True

        except Exception as e:
            self.logger.error(f"记录数据失败: {str(e)}")
            return False

    def _cleanup(self):
        """清理资源"""
        self.log_file = None
        self.csv_writer = None
        self.is_logging = False
        self.filename = None

    def get_logging_status(self) -> Dict[str, Any]:
        """获取记录状态"""
        return {
            'is_logging': self.is_logging,
            'filename': self.filename,
            'field_count': len(self.fieldnames) if self.fieldnames else 0
        }

    def __del__(self):
        """析构函数，确保文件关闭"""
        if self.is_logging:
            self.stop_logging()